<template>
  <view class="payment-page">
    <!-- 订单信息 -->
    <view class="order-info-section">
      <view class="section-title">订单信息</view>
      <view class="info-item">
        <text class="label">订单号：</text>
        <text class="value">{{ orderInfo.orderNo }}</text>
      </view>
      <view class="info-item">
        <text class="label">预约球桌：</text>
        <text class="value">{{ orderInfo.productName }}</text>
      </view>
      <view class="info-item">
        <text class="label">预约时间：</text>
        <view class="value time-list">
          <view v-for="(time, index) in orderInfo.selectedTimes" :key="index" class="time-item">
            {{ time }}
          </view>
        </view>
      </view>
    </view>
    
    <!-- 费用明细 -->
    <view class="cost-section">
      <view class="section-title">费用明细</view>
      <view class="cost-item">
        <text class="label">单价</text>
        <text class="value">¥{{ orderInfo.price }}</text>
      </view>
      <view class="cost-item">
        <text class="label">数量：</text>
        <text class="value">x{{ orderInfo.quantity }}</text>
      </view>
      <view class="cost-item total">
        <text class="label">合计</text>
        <text class="value total-price">¥{{ orderInfo.totalAmount }}</text>
      </view>
    </view>
    
    <!-- 微信支付方式 -->
    <view class="payment-method-section">
      <view class="section-title">支付方式</view>
      <view class="payment-methods">
        <view class="method-item active">
          <image :src="wechatPaymentMethod.icon" class="method-icon" mode="widthFix"></image>
          <text class="method-name">{{ wechatPaymentMethod.name }}</text>
          <view class="checkmark">
            <uni-icons type="checkmark" size="24" color="#3b82f6"></uni-icons>
          </view>
        </view>
      </view>
    </view>
    
    <!-- 底部支付按钮 -->
    <view class="footer">
      <button class="pay-button" @click="confirmPayment" :disabled="!canPay">
        立即支付 ¥{{ orderInfo.totalAmount }}
      </button>
    </view>
    
    <!-- 支付结果弹窗 -->
    <view class="payment-modal" v-if="showPaymentModal">
      <view class="modal-content">
        <view class="modal-icon" :class="paymentResult.status">
          <text v-if="paymentResult.status === 'success'">✓</text>
          <text v-else>✗</text>
        </view>
        <view class="modal-title">{{ paymentResult.title }}</view>
        <view class="modal-message">{{ paymentResult.message }}</view>
        <view class="modal-actions">
          <button class="modal-button" @click="closePaymentModal">{{ paymentResult.buttonText }}</button>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
import { onLoad, onShow } from '@dcloudio/uni-app';
import { getOrderDetails, payOrder } from '@/services/order.js';
import { formatDateTimeRange } from '@/utils/date.js';

// 订单信息
const orderInfo = ref({
  orderNo: '',
  productName: '',
  selectedTimes: [],
  price: 0,
  quantity: 0,
  totalAmount: 0,
  dateTimeRangeList: []
});

// 微信支付方式
const wechatPaymentMethod = ref({
  id: 'wechat',
  name: '微信支付',
  icon: '/static/image/wechat-pay.png'
});

// 支付结果弹窗相关
const showPaymentModal = ref(false);
const paymentResult = ref({
  status: 'success',
  title: '',
  message: '',
  buttonText: ''
});

// 是否可支付
const canPay = computed(() => {
  return Number(orderInfo.value.totalAmount) > 0 && 
         orderInfo.value.orderNo && 
         orderInfo.value.selectedTimes.length > 0;
});

// 确认支付
const confirmPayment = async () => {
  if (!canPay.value) {
    uni.showToast({
      title: '订单信息异常，无法支付',
      icon: 'none',
      duration: 1500
    });
    return;
  }
  
  uni.showLoading({
    title: '支付中...',
    mask: true
  });
  
  try {
    // 调用支付接口
    const response = await payOrder(orderInfo.value.orderNo);
    
    if (response.code === 200) {
      // 支付成功
      showPaymentResult('success', '支付成功', '订单支付成功', '查看订单');
    } else {
      // 支付失败
      showPaymentResult('error', '支付失败', response.message || '支付失败，请重试', '重新支付');
    }
  } catch (error) {
    console.error('支付失败:', error);
    showPaymentResult('error', '支付失败', '网络异常，请重试', '重新支付');
  } finally {
    uni.hideLoading();
  }
};

// 显示支付结果
const showPaymentResult = (status, title, message, buttonText) => {
  paymentResult.value = {
    status,
    title,
    message,
    buttonText
  };
  showPaymentModal.value = true;
};

// 关闭支付结果弹窗
const closePaymentModal = () => {
  showPaymentModal.value = false;
  
  // 如果支付成功，跳转到订单详情页
  if (paymentResult.value.status === 'success') {
    setTimeout(() => {
      uni.redirectTo({
        url: `/pages/mine/orderDetail?orderNo=${orderInfo.value.orderNo}`
      });
    }, 500);
  }
};

// 获取订单详情
const fetchOrderDetails = async (orderNo) => {
  try {
    uni.showLoading({
      title: '加载中...'
    });
    
    const response = await getOrderDetails(orderNo);
    
    if (response.code === 200 && response.data) {
      const orderData = response.data;
      
      // 处理预约时间
      let selectedTimes = [];
      let date = '';
      
      // 首先检查 dateTimeRangeList
      if (orderData.dateTimeRangeList && orderData.dateTimeRangeList.length > 0) {
        const { formattedDate, formattedTimeSlot } = formatDateTimeRange(orderData.dateTimeRangeList);
        date = formattedDate;
        selectedTimes = formattedTimeSlot.split(', ');
      } 
      // 如果没有 dateTimeRangeList，检查 priceDateTimeRangeVOList
      else if (orderData.priceDateTimeRangeVOList && orderData.priceDateTimeRangeVOList.length > 0) {
        // 从 priceDateTimeRangeVOList 中提取预约时间
        const startTime = orderData.priceDateTimeRangeVOList[0].startTime;
        if (startTime) {
          // 格式化 startTime，假设格式为 "YYYY-MM-DD HH:mm:ss"
          const datePart = startTime.split(' ')[0];
          date = datePart;
          
          // 获取星期几
          const dateObj = new Date(datePart);
          const weekdayMap = {
            0: '周日',
            1: '周一',
            2: '周二',
            3: '周三',
            4: '周四',
            5: '周五',
            6: '周六'
          };
          const weekday = weekdayMap[dateObj.getDay()];
          date = `${datePart} (${weekday})`;
          
          // 如果有多个时间段，显示所有时间段
          if (orderData.priceDateTimeRangeVOList.length > 1) {
            selectedTimes = orderData.priceDateTimeRangeVOList.map(item => {
              return item.startTime.split(' ')[1]?.substring(0, 5) + '-' + item.endTime.split(' ')[1]?.substring(0, 5);
            });
          } else {
            // 单个时间段
            const endTime = orderData.priceDateTimeRangeVOList[0].endTime?.split(' ')[1]?.substring(0, 5);
            const startTime = orderData.priceDateTimeRangeVOList[0].startTime?.split(' ')[1]?.substring(0, 5);
            selectedTimes = [`${startTime}-${endTime}`];
          }
        }
      }
      
      orderInfo.value = {
        orderNo: orderData.orderNo,
        productName: orderData.productName || '乒乓球桌',
        selectedTimes: selectedTimes,
        price: orderData.orderPayPrice || orderData.price || orderData.totalAmount / (orderData.dateTimeRangeList?.length || 1),
        quantity: orderData.dateTimeRangeList?.length || orderData.priceDateTimeRangeVOList?.length || 1,
        totalAmount: orderData.orderPayPrice || orderData.totalAmount,
        date: date,
        dateTimeRangeList: orderData.dateTimeRangeList || []
      };
    } else {
      uni.showToast({
        title: response.message || '获取订单详情失败',
        icon: 'none'
      });
    }
  } catch (error) {
    console.error('获取订单详情失败:', error);
    uni.showToast({
      title: '网络异常，请重试',
      icon: 'none'
    });
  } finally {
    uni.hideLoading();
  }
};

// 根据状态生成订单状态显示文本
const generateOrderStatus = (status) => {
  switch (status) {
    case 'pending':
      return '待支付';
    case 'paid':
      return '已支付';
    case 'completed':
      return '待核销';
    case 'cancelled':
      return '取消支付';
    case 'refunded':
      return '已退款';
    default:
      return '未知状态';
  }
};

// 页面加载时初始化
onLoad((options) => {
  if (options?.orderNo) {
    fetchOrderDetails(options.orderNo);
  } else {
    uni.showToast({
      title: '缺少订单信息',
      icon: 'none',
      duration: 1500
    });
    
    setTimeout(() => {
      uni.navigateBack();
    }, 1500);
  }
});
</script>

<style lang="scss" scoped>
.payment-page {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding: 20rpx;
  padding-bottom: 120rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  margin-bottom: 20rpx;
  padding: 10rpx 0;
  color: #333;
}

.order-info-section,
.cost-section,
.payment-method-section {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.05);
}

.info-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  border-bottom: 1rpx solid #f5f5f5;
  
  &:last-child {
    border-bottom: none;
  }
  
  .label {
    font-size: 28rpx;
    color: #666;
    width: 140rpx;
  }
  
  .value {
    font-size: 28rpx;
    color: #333;
    text-align: right;
    flex: 1;
  }
  
  .time-list {
    display: flex;
    flex-wrap: wrap;
    justify-content: flex-end;
    gap: 12rpx;
    
    .time-item {
      background-color: #f0f7ff;
      color: #3b82f6;
      padding: 6rpx 16rpx;
      border-radius: 20rpx;
      font-size: 24rpx;
    }
  }
}

.cost-item {
  display: flex;
  justify-content: space-between;
  padding: 15rpx 0;
  
  .label {
    font-size: 28rpx;
    color: #666;
  }
  
  .value {
    font-size: 28rpx;
    color: #333;
  }
  
  &.total {
    border-top: 1rpx solid #f0f0f0;
    margin-top: 10rpx;
    padding-top: 20rpx;
    
    .value.total-price {
      font-size: 36rpx;
      color: #e60012;
      font-weight: bold;
    }
  }
}

.payment-methods {
  .method-item {
    display: flex;
    align-items: center;
    padding: 20rpx;
    border: 2rpx solid #e0e0e0;
    border-radius: 12rpx;
    margin-bottom: 20rpx;
    transition: border-color 0.3s, background-color 0.3s;
    
    &.active {
      border-color: #3b82f6;
      background-color: #f0f7ff;
    }
    
    &:last-child {
      margin-bottom: 0;
    }
    
    .method-icon {
      width: 56rpx;
      height: 56rpx;
      margin-right: 20rpx;
      object-fit: contain;
    }
    
    .method-name {
      flex: 1;
      font-size: 28rpx;
      color: #333;
    }
    
    .checkmark {
      width: 40rpx;
      height: 40rpx;
      display: flex;
      align-items: center;
      justify-content: center;
    }
  }
}

.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #fff;
  padding: 20rpx 30rpx;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.1);
  
  .pay-button {
    width: 100%;
    background: #3b82f6;
    color: white;
    border: none;
    border-radius: 50rpx;
    padding: 24rpx;
    font-size: 32rpx;
    font-weight: 500;
    
    &:disabled {
      background: #ccc;
      color: #fff;
    }
    
    &::after {
      border: none;
    }
  }
}

/* 支付结果弹窗样式 */
.payment-modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: #fff;
  border-radius: 16rpx;
  padding: 40rpx;
  width: 80%;
  text-align: center;
}

.modal-icon {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 48rpx;
  margin: 0 auto 20rpx;
  
  &.success {
    background-color: #e8f7ef;
    color: #2ab363;
  }
  
  &.error {
    background-color: #fdeeee;
    color: #e64a19;
  }
}

.modal-title {
  font-size: 36rpx;
  font-weight: bold;
  margin-bottom: 10rpx;
  color: #333;
}

.modal-message {
  font-size: 28rpx;
  color: #666;
  margin-bottom: 30rpx;
}

.modal-button {
  background-color: #3b82f6;
  color: white;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 40rpx;
  font-size: 32rpx;
  
  &::after {
    border: none;
  }
}
</style>